﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.EventSystems;
using Game.Scripts.Managers;

public class PartyController : MonoBehaviour {


    public string Name { get { return transform.gameObject.name; } }


    public List<SteveBrain> PeopleInParty {
        get { return peopleInParty; }
    }
    private List<SteveBrain> peopleInParty = new List<SteveBrain>();

    internal Vector3 destination = Vector3.zero;

    private Vector3 swarmCentroid;
    private bool isHavingFun = false;


    public void Update() { 
        //continuously updates the centroid once per frame (this has a 
        //time complexity of O(1) avg per frame, versus the O(n) avg per frame
        //with a swarm of n boids).
        Vector3 sum = Vector3.zero;
        foreach (SteveBrain item in this.peopleInParty){
            Boid b = item.GetComponent<Boid>();
            sum += b.transform.position;
        }
        this.swarmCentroid = sum / this.peopleInParty.Count;
    }



    private void startHavingFun() {
        BuildingManager manager = BuildingManager.instance;
        if (manager != null) {
            BuildingPrototype prototype = manager.getPrototypeByName("bar");
            if (prototype != null) {
                int barCount = prototype.instanceCount;
                if (barCount > 0) {
                    int randomBarIndex = Random.Range(0, barCount - 1);
                    Building bar = prototype.getInstanceByIndex(randomBarIndex);
                    if (bar != null) {
                        //setting randez-vous destination point
                        Vector3 randezVousPoint = bar.transform.position;
                        this.destination = randezVousPoint;

                        //begins flocking
                        foreach (SteveBrain agent in this.peopleInParty) {
                            agent.havingFun = true;
                        }
                    }
                }
            }
        }
    }



    private void stopHavingFun() { 
        foreach(SteveBrain member in this.peopleInParty){
            member.havingFun = false;
        }
    }



    public bool havingFun {
        get {
            return this.isHavingFun;
        }

        set {
            this.isHavingFun = value;
            if (this.isHavingFun) {
                this.startHavingFun();
            } else {
                this.stopHavingFun();
            }
        }
    }



    public Vector3 Center {
        get {
            return this.swarmCentroid;
        }
    }
}
